﻿using BootstrapBlazor.Components;
using Common.Api.Client;
using Cyss.Core;
using CyssBlazor.Shared.Infrastructure;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CyssBlazor.Shared.Components
{
    public class InputUploadFile : InputUpload<int>
    {
        [Inject]
        private IJSRuntime _JSRuntime { set; get; }

        /// <summary>
        /// 下载按钮Id
        /// </summary>
        private string DownloadId = Guid.NewGuid().ToString().Replace("-", "");

        /// <summary>
        /// 元素Index
        /// </summary>
        private int index = 0;

        /// <summary>
        /// 正在上传图标
        /// </summary>
        private string LoadingIcon = "fa fa-spinner fa-spin fa-fw";

        /// <summary>
        /// 
        /// </summary>
        private string Url { set; get; }


        [Parameter]
        public virtual string AllowFileType { set; get; }

        /// <summary>
        /// 最多同时传入文件个数
        /// </summary>
        [Parameter]
        public int MaximumFileCount { set; get; } = 1;

        /// <summary>
        /// 单个文件最大字节  默认5m
        /// </summary>
        [Parameter]
        public int MaxAllowedSize { set; get; } = 5 * 1024 * 1024;



        public InputUploadFile()
        {
            this.OnChange = OnFileChange;
            this.OnDelete = DeleteFile;
        }

        private async Task<bool> DeleteFile(UploadFile file)
        {
            this.Url = string.Empty;
            await ToggleDownloadButton();
            this.CurrentFile.FileName = string.Empty;
            return true;
        }

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (IsRedrawing)
            {
                await _JSRuntime.InvokeVoidAsync(null, "bb_add_button", DownloadId);
                await ToggleDownloadButton();
                IsRedrawing = false;
            }
            if (firstRender)
            {
                await LoadFileName();
                await ToggleDownloadButton();

            }
            await base.OnAfterRenderAsync(firstRender);
        }

        /// <summary>
        /// 显示下载按钮
        /// </summary>
        /// <returns></returns>
        private async Task ToggleDownloadButton()
        {
            if (!string.IsNullOrWhiteSpace(this.Url))
            {
                await _JSRuntime.InvokeVoidAsync(null, "bb_show_button", DownloadId);
            }
            else
            {
                await _JSRuntime.InvokeVoidAsync(null, "bb_hide_button", DownloadId);
            }
        }

        private async Task OnFileChange(UploadFile file)
        {
            if (Verification(file.File) == false)
            {
                return;
            }

            string browserButtonIcon = BrowserButtonIcon;
            BrowserButtonIcon = LoadingIcon;
            SetDisable(true);

            var imageFile = file.File;
            var operateResult = await CommonClientFactory.Download.AsyncUpload(imageFile.OpenReadStream(maxAllowedSize: long.MaxValue), imageFile.Name);
            if (operateResult.IsSuccess)
            {
                this.CurrentValue = operateResult.Data.FileId;
                this.Value = operateResult.Data.FileId;
                this.Url = $"http://localhost:55151/Download/GetFileById?Id={this.Value}";
            }
            else
            {
                this.CurrentFile.FileName = string.Empty;
                this.Url = string.Empty;
            }
            BrowserButtonIcon = browserButtonIcon;
            IsDisabled = false;
            await ToggleDownloadButton();
            await InvokeAsync(StateHasChanged);
        }

        /// <summary>
        /// 初始加载图片
        /// </summary>
        private async Task LoadFileName()
        {
            if (this.CurrentFile == null)
            {
                this.CurrentFile = new UploadFile();
            }
            if (this.Value > 0)
            {
                await InvokeAsync(StateHasChanged);
                var operateResult = await CommonClientFactory.Download.GetDownloadById(this.Value);
                if (operateResult.IsSuccess)
                {
                    this.CurrentFile.FileName = operateResult.Data.FileName;
                    this.Url = $"http://localhost:55151/Download/GetFileById?Id={this.Value}";
                }
                await InvokeAsync(StateHasChanged);
            }
            else
            {
                this.CurrentFile.FileName = string.Empty;
            }
        }


        private bool IsRedrawing = false;
        protected override void BuildRenderTree(RenderTreeBuilder __builder)
        {
            base.BuildRenderTree(__builder);
            __builder.AddContent(index++, AddButtonRenderFragment());
            IsRedrawing = true;
        }


        /// <summary>
        /// 添加下载链接按钮
        /// </summary>
        /// <returns></returns>
        private RenderFragment AddButtonRenderFragment()
        {
            var BodyTemplate = new RenderFragment(builder =>
            {
                builder.OpenElement(index++, "a");
                builder.AddAttribute(index++, "class", "btn btn-success");
                builder.AddAttribute(index++, "style", "display: none");
                builder.AddAttribute(index++, "id", DownloadId);
                builder.AddAttribute(index++, "href", this.Url);

                builder.OpenElement(index++, "i");
                builder.AddAttribute(index++, "class", "fa fa-download");
                builder.CloseElement();

                builder.OpenElement(index++, "span");
                builder.AddContent(index++, "下载");
                builder.CloseElement();

                builder.CloseElement();
            });
            return BodyTemplate;
        }

        protected bool Verification(IBrowserFile file)
        {

            if (file.Size > MaxAllowedSize)
            {
                return false;
            }

            //if (!string.IsNullOrWhiteSpace(AllowFileType) && !AllowFileType.Split(",").Contains(System.IO.Path.GetExtension(file.Name)))
            //{
            //    return false;
            //}
            return true;
        }

    }
}
